package com.gaga.console.core.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.gaga.common.enums.DelFlag;
import com.gaga.console.base.entity.PageParams;
import com.gaga.console.base.mybatisplus.LambdaQueryWrapperExt;
import com.gaga.console.base.service.impl.SuperServiceImpl;
import com.gaga.console.core.entity.SysRole;
import com.gaga.console.core.entity.SysRoleMenu;
import com.gaga.console.core.entity.SysUserRole;
import com.gaga.console.core.mapper.SysRoleMapper;
import com.gaga.console.core.service.SysRoleMenuService;
import com.gaga.console.core.service.SysRoleService;
import com.gaga.console.core.service.SysUserRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 角色表 服务实现类
 * </p>
 *
 * @author liujia
 * @since 2022-07-14
 */
@Service
public class SysRoleServiceImpl extends SuperServiceImpl<SysRoleMapper, SysRole> implements SysRoleService {

    @Autowired
    private SysRoleMenuService sysRoleMenuService;

    @Autowired
    private SysUserRoleService sysUserRoleService;


    @Override
    public IPage<SysRole> getPageList(PageParams<SysRole> data) {

        LambdaQueryWrapperExt<SysRole> wraps = new LambdaQueryWrapperExt<>();
        wraps.eq(SysRole::getDelFlag, DelFlag.OK.getCode());
        data.buildSpecWrap(wraps, SysRole.class);

        IPage<SysRole> sysRolePage = this.baseMapper.selectPage(data.buildPage(), wraps);

        List<SysRole> records = sysRolePage.getRecords();
        // 将权限列表添加到分页列表中
        List<SysRole> collect = records.stream().map(sysRole -> sysRole.setMenu(this.permissionIdList(sysRole.getId())))
                .collect(Collectors.toList());
        // 用新的List赋值分页对象
        sysRolePage.setRecords(collect);

        return sysRolePage;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean customSave(SysRole sysRole) {
        this.saveOrUpdate(sysRole);
        if (ObjectUtil.isNotEmpty(sysRole.getMenu())) {
            List<SysRoleMenu> collect = sysRole.getMenu().stream().map(s -> {
                SysRoleMenu sysRoleMenu = new SysRoleMenu();
                sysRoleMenu.setMenuId(Long.valueOf(s));
                sysRoleMenu.setRoleId(sysRole.getId());
                return sysRoleMenu;
            }).collect(Collectors.toList());
            // 根据角色ID删除所有菜单值
            sysRoleMenuService.remove(Wrappers.<SysRoleMenu>lambdaQuery().eq(SysRoleMenu::getRoleId, sysRole.getId()));
            // 重新写入角色对应的权限值
            sysRoleMenuService.saveBatch(collect);
        }
        return Boolean.TRUE;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean batchDeleteByIds(String ids) {
        String[] idArray = null;
        if (StrUtil.isNotBlank(ids)) {
            idArray = ids.split(",");
            Arrays.stream(idArray).forEach(s -> {
                // 根据roleId清理掉此角色下面的所有菜单信息
                sysRoleMenuService.remove(Wrappers.<SysRoleMenu>lambdaQuery().eq(SysRoleMenu::getRoleId, s));
                // 根据roleId清理掉用户里的角色信息，需要下次重新授权
                sysUserRoleService.remove(Wrappers.<SysUserRole>lambdaQuery().eq(SysUserRole::getRoleId, s));
                this.update(Wrappers.<SysRole>lambdaUpdate().eq(SysRole::getId, s).set(SysRole::getDelFlag, DelFlag.DELETED.getCode()).set(SysRole::getDeleteTime, new Date()));
            });
        }
        return Boolean.TRUE;
    }

    private List<String> permissionIdList(Long roleId) {
        LambdaQueryWrapper<SysRoleMenu> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SysRoleMenu::getRoleId, roleId);
        List<SysRoleMenu> sysRolePermissions = sysRoleMenuService.list(lambdaQueryWrapper);
        List<String> list = sysRolePermissions.stream().map(sysRolePermission -> {
            String menuId = sysRolePermission.getMenuId().toString();
            return menuId;
        }).collect(Collectors.toList());
        return list;
    }
}
